package handler

// func newProxyHandler() {

// }

// package handler

import (
	"encoding/json"
	"io"
	"iptv_server/v3/v2_src/handler/middleware"
	"iptv_server/v3/v2_src/utils/cache"

	"net/http"
	"strings"
	"time"
)

func initPlaying(mux *http.ServeMux, middles ...middleware.MiddleWare) {
	h1 := &playing{
		playinStringCache: cache.NewCache[string]("playing string cache", time.Hour*time.Duration(32)), // 5 Hour->32
	}

	h2 := middleware.ApplyMiddles(h1, middles...)

	// parsers = make(map[string]parser.ParserBuilder)
	// parsers["m3u"] = parser.NewM3U
	// parsers["m3u"]=&

	// http.DefaultServeMux.Handle()

	// 这个不是代理, 是读取参数 代请求.
	mux.Handle("/api/playing", h2)

	mux.HandleFunc("/api/playing_clear_cache", func(w http.ResponseWriter, r *http.Request) {
		h1.clear()
	})
}

type playing struct {
	playinStringCache *cache.Cache[string]
}

func (p *playing) clear() {
	p.playinStringCache.Clear()
}

// "/api/proxy/"
// "0:/1:api/2:proxy/3:"
func (p *playing) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	if r.Method == http.MethodGet {
		m := p.playinStringCache.GetAll()
		if bs, err := json.Marshal(m); err == nil {
			w.Write(bs)
		} else {
			w.WriteHeader(http.StatusNotFound)
		}
		return
	}

	if r.Method == http.MethodPost {
		defer r.Body.Close()
		if bs, err := io.ReadAll(r.Body); err == nil {
			host := strings.Split(r.RemoteAddr, ":")[0]
			p.playinStringCache.Save(host, string(bs))
		}
		w.Write([]byte("OK\n\n"))
		return
	}
}
